package pilgun.Multithread.MergeSort;

import java.util.Arrays;


public class MergeSort implements Runnable{
	private int[] A;
	private int p;
	private int r;
	MergeSort (int[] A, int p , int r){
		this.A = A;
		this.p = p;
		this.r = r;
	}
	
	public void merge(int[] A , int p, int q, int r){
	   int i = p;
	   int j = q + 1;
	   int[] tmp = new int[r-p+1];
	   for(int step = 0; step < r - p + 1; step++) {
		     if((j > r) || ((i <= q) && (A[i] < A[j]))) {
		       tmp[step] = A[i];
		       i++;
		     } else {
		       tmp[step] = A[j];
		       j++;
		     }
		   }
		   for(int step = 0; step < r-p+1; step++) {
		     A[p+step] = tmp[step];
		   }
		   
	}
	
	public void run(){
		if (p<r){
			int q = (p+r)/2;
			Thread firstHalf = new Thread(new MergeSort(A, p, q));
			firstHalf.start();
			MergeSort lastHalf = new MergeSort(A, q+1, r);
			lastHalf.run();
			try {
				firstHalf.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			int[] T = Arrays.copyOf(A, A.length);
			PMerge apMerge = new PMerge(T, p, q, q+1, r, A, p);
			apMerge.run();
			}
			
		}
}
